//
//  WMDownloadManager.m
//  WholeMusic
//
//  Created by quanxiong on 2018/2/24.
//  Copyright © 2018年 quanxiong. All rights reserved.
//

#import "WMDownloadManager.h"
#import <AFNetworking/AFNetworking.h>
#import <YYKit/YYKit.h>

@interface WMDownloadManager ()

@property (strong, nonatomic) AFURLSessionManager *sessionManager;

@end


@implementation WMDownloadManager

+ (instancetype)sharedManager {
    static WMDownloadManager *s_manager;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        s_manager = [[self alloc] init];
    });
    return s_manager;
}

- (instancetype)init {
    if (self = [super init]) {
        NSURLSessionConfiguration *configuration =
        [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@"com.whole.music"];
        [configuration setAllowsCellularAccess:YES];
        [configuration setNetworkServiceType:NSURLNetworkServiceTypeBackground];
        _sessionManager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
        _sessionManager.operationQueue.maxConcurrentOperationCount = 3;
        
    }
    return self;
}

- (void)addDownloadTaskWithUrl:(NSString *)url
                      filePath:(id)filePath
                      progress:(void (^)(NSProgress *downloadProgress))downloadProgressBlock
             completionHandler:(void (^)(NSURLResponse *response, NSURL *filePath, NSError *error))completionHandler
{
    NSURL *downloadURL = [NSURL URLWithString:url];
    NSURLRequest *request = [NSURLRequest requestWithURL:downloadURL];
    NSURLSessionDownloadTask *task =
    [_sessionManager downloadTaskWithRequest:request
                                    progress:downloadProgressBlock
                                 destination:[self destinationBlockWithFilePath:filePath]
                           completionHandler:completionHandler];
    [task resume];
}

- (NSURL * _Nonnull(^)(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response))destinationBlockWithFilePath:(id)filePath {
    return ^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        if ([filePath isKindOfClass:NSString.class]) {
            return [NSURL fileURLWithPath:(NSString *)filePath];//[NSURL URLWithString:(NSString *)filePath];
        }
        return filePath;
    };
}

@end
